import { DeviceType, BrowserTypeBrief } from "@/const/emun";

/***
 * @file 图片文件
 * @option object 配置对象 {quality:0.7,scale:number}
 *   @quality 压缩后的图片质量 @default 0.7
 *   @scale 图片压缩后宽高大小的缩小值  @default 1
 *
 */

export function compressFile(
  file: any,
  option: {
    quality: number;
    scale?: number;
  } = {
    quality: 0.6,
    scale: 1,
  }
): Promise<any> {
  return new Promise((resolve, reject) => {
    console.log(file.size);
    if (file.size < 204800) {
      resolve(file);
    }
    let fileObj = file;
    let scale = option.scale || 1;
    let reader = new FileReader();
    reader.readAsDataURL(fileObj); //转base64
    reader.onload = function (e: Event) {
      try {
        let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
        image.src = (e.target as any).result;
        image.onload = function () {
          let canvas = document.createElement("canvas"), // 新建canvas
            context: any = canvas.getContext("2d"),
            imageWidth = image.width / scale, //压缩后图片的大小
            imageHeight = image.height / scale,
            data = "";
          canvas.width = imageWidth;
          canvas.height = imageHeight;
          context.drawImage(image, 0, 0, imageWidth, imageHeight);
          data = canvas.toDataURL("image/jpeg", option.quality); // 输出压缩后的base64
          let arr = data.split(","),
            // @ts-ignore
            mime = arr[0].match(/:(.*?);/)[1], // 转成blob
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
          }
          let files = new window.File(
            [new Blob([u8arr], { type: mime })],
            "test.jpeg",
            { type: "image/jpeg" }
          ); // 转成file
          resolve(files); // 回调
        };
      } catch (error) {
        reject(error);
      }
    };
  });
}

export function mockApi(data = {}, delay = 1000, shouldFail = false) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldFail) {
        reject(new Error("API request failed!"));
      } else {
        resolve({ success: true, data });
      }
    }, delay);
  });
}

// 判断浏览器类型
export function checkBrowser(): BrowserTypeBrief {
  const ua = navigator.userAgent.toLowerCase();
  if (ua.indexOf("micromessenger") !== -1) {
    return BrowserTypeBrief.WECHAT; // 微信浏览器
  } else if (ua.indexOf("mobile") !== -1) {
    // return "WeChat Browser";
    return BrowserTypeBrief.MOBILE; // 移动端本地浏览器
  } else {
    return BrowserTypeBrief.DESKTOP; // 桌面浏览器
  }
}

// 判断设备类型
export function detectDevice(): DeviceType {
  const userAgent = navigator.userAgent;
  let deviceType = DeviceType.UNKNOWN;
  if (/android/i.test(userAgent)) {
    deviceType = DeviceType.ANDROID;
  } else if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
    deviceType = DeviceType.IOS;
  } else if (/Windows|Macintosh|Linux/.test(userAgent)) {
    deviceType = DeviceType.DESKTOP;
  }
  return deviceType;
}
//   // 使用方式（try/catch 处理错误）
//   async function fetchData() {
//     try {
//       const response = await mockApi({ id: 1 }, 1000, false);
//       console.log(response);
//     } catch (error) {
//       console.error("Error:", error.message); // Error: API request failed!
//     }
//   }

//   fetchData();
